package com.ytq.pratice.spring.template;

import com.ytq.pratice.spring.template.dao.RowMapper;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author yuantongqin
 * @date 2018/9/16 上午11:08
 */
public  class JdbcTemplate {

    private DataSource dataSource;

    public JdbcTemplate(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    /**
     * 定义一个查询方法
     */

    public List<Object> getQuery(String statement, RowMapper<?> row){
        List<Object> lists = new ArrayList<>();
        try {
            Connection conn = dataSource.getConnection();
            PreparedStatement preparedStatement = conn.prepareStatement(statement);
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()){
                lists.add(row.rowResult(resultSet));
            }

            resultSet.close();
            preparedStatement.close();
            conn.close();

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return lists;
    }



}
